"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } });
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __exportStar = (this && this.__exportStar) || function(m, exports) {
    for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (_) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
__exportStar(require("./decorator"), exports);
var redis_1 = __importDefault(require("redis"));
var fs_1 = __importDefault(require("fs"));
var path_1 = __importDefault(require("path"));
var util_1 = require("util");
var decorator_1 = require("./decorator");
var CONFIG_FILE_PATH = path_1.default.resolve(__dirname, '../../../redisconfig.json');
var options = {
    host: '127.0.0.1',
    port: 6379
};
if (fs_1.default.existsSync(CONFIG_FILE_PATH)) {
    try {
        options = JSON.parse(fs_1.default.readFileSync(CONFIG_FILE_PATH, { encoding: 'utf-8' }));
    }
    catch (error) {
        console.log(error);
    }
}
else {
    // console.log('redisconfig.json 配置文件不存在，将使用默认配置')
}
// 判断是否有相关的环境变量
if (process.env.REDIS_HOST) {
    options.host = process.env.REDIS_HOST;
}
if (process.env.REDIS_PORT) {
    options.port = Number(process.env.REDIS_PORT);
}
if (process.env.REDIS_AUTH_PASS) {
    options.auth_pass = process.env.REDIS_AUTH_PASS;
}
var client;
// 是否连接 redis
if (process.env.CONNECT_REDIS && String(process.env.CONNECT_REDIS) === 'true') {
    client = redis_1.default.createClient(options);
}
client && client.on('ready', function () {
    // console.log('redis 连接成功')
    Redis.isReady = true;
});
client && client.on('error', function (error) {
    console.log(error);
    Redis.isReady = false;
});
var Redis = /** @class */ (function () {
    function Redis() {
    }
    var _a;
    _a = Redis;
    Redis.isReady = false;
    Redis.client = client;
    // 删除
    // static del = promisify(client.del).bind(client) as (key: string) => Promise<string>
    // 删除
    Redis.del = function (key) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(_a, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!client)
                        throw new Error('redis 尚未连接');
                    return [4 /*yield*/, (0, util_1.promisify)(client.del).bind(client)(key)];
                case 1: return [2 /*return*/, _b.sent()];
            }
        });
    }); };
    // 字符串
    // static set = promisify(client.set).bind(client) as (key: string, value: string | number) => Promise<string>
    Redis.set = function (key, value) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(_a, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!client)
                        throw new Error('redis 尚未连接');
                    return [4 /*yield*/, (0, util_1.promisify)(client.set).bind(client)(key, value)];
                case 1: return [2 /*return*/, _b.sent()];
            }
        });
    }); };
    // static get = promisify(client.get).bind(client) as (key: string) => Promise<string>
    Redis.get = function (key) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(_a, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!client)
                        throw new Error('redis 尚未连接');
                    return [4 /*yield*/, (0, util_1.promisify)(client.get).bind(client)(key)];
                case 1: return [2 /*return*/, _b.sent()];
            }
        });
    }); };
    // hashmap
    Redis.hmset = function (key, arg1) {
        if (!client)
            throw new Error('redis 尚未连接');
        return new Promise(function (resolve, reject) {
            var arg = (0, decorator_1.instance2Object)(arg1);
            client.hmset(key, arg, function (err, val) {
                err ? reject(err) : resolve(val);
            });
        });
    };
    Redis.hmget = function (key, constructor) {
        if (!client)
            throw new Error('redis 尚未连接');
        var meta = constructor ? (0, decorator_1.getMeta)(constructor) : null;
        return new Promise(function (resolve, reject) {
            client.hmget(key, meta ? meta.keys : null, function (err, vals) {
                if (err) {
                    reject(err);
                }
                else {
                    if (constructor) {
                        var obj_1 = {};
                        meta.keys.forEach(function (key, index) {
                            var MetaData = meta.MetaDatas[key];
                            if (MetaData && vals[index] !== null) {
                                obj_1[key] = MetaData(vals[index]);
                            }
                            else {
                                obj_1[key] = vals[index];
                            }
                        });
                        resolve(obj_1);
                    }
                    else {
                        resolve(vals);
                    }
                }
            });
        });
    };
    // 数组
    Redis.L_META_DATA_KEY = 'L_META_DATA_KEY';
    // static lpush = promisify(client.lpush).bind(client) as (key: string, arg1: string | string[]) => Promise<number>
    Redis.lpush = function (key, arg1) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(_a, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!client)
                        throw new Error('redis 尚未连接');
                    return [4 /*yield*/, (0, util_1.promisify)(client.lpush).bind(client)(key, arg1)];
                case 1: return [2 /*return*/, _b.sent()];
            }
        });
    }); };
    // static lrange = promisify(client.lrange).bind(client) as (key: string, start: number, stop: number) => Promise<string[]>
    Redis.lrange = function (key, start, stop) { return __awaiter(void 0, void 0, void 0, function () {
        return __generator(_a, function (_b) {
            switch (_b.label) {
                case 0:
                    if (!client)
                        throw new Error('redis 尚未连接');
                    return [4 /*yield*/, (0, util_1.promisify)(client.lrange).bind(client)(key, start, stop)];
                case 1: return [2 /*return*/, _b.sent()];
            }
        });
    }); };
    Redis.pushList = function (key, list, isSaveMeta) {
        if (isSaveMeta === void 0) { isSaveMeta = false; }
        if (!client)
            throw new Error('redis 尚未连接');
        return Promise.all([
            Redis.lpush(key, list.map(function (item) { return String(item); })),
            isSaveMeta && Redis.lpush(key + Redis.L_META_DATA_KEY, list.map(function (item) { return typeof item; })),
        ]);
    };
    Redis.setList = function (key, list, isSaveMeta) {
        if (isSaveMeta === void 0) { isSaveMeta = false; }
        if (!client)
            throw new Error('redis 尚未连接');
        client.del(key);
        client.del(key + Redis.L_META_DATA_KEY);
        return Redis.pushList(key, list, isSaveMeta);
    };
    Redis.getList = function (key) {
        if (!client)
            throw new Error('redis 尚未连接');
        return new Promise(function (resolve, reject) {
            Promise.all([
                Redis.lrange(key, 0, -1),
                Redis.lrange(key + Redis.L_META_DATA_KEY, 0, -1),
            ]).then(function (_b) {
                var list = _b[0], metaList = _b[1];
                var reverseListmMetaList = metaList.reverse();
                var result = list.reverse().map(function (item, index) {
                    try {
                        if (reverseListmMetaList[index] === 'number') {
                            return Number(item);
                        }
                    }
                    catch (error) {
                        console.log('redis 数组类型转换错误');
                    }
                    return item;
                });
                resolve(result);
            }).catch(reject);
        });
    };
    return Redis;
}());
exports.default = Redis;
